﻿using System;
using System.Collections.Generic;
using UnityEngine;
using PnFramework.Unity;

namespace UnitySmallTheater
{
    public class PlayerMgr
    {
        private Dictionary<int, Player> mPlayers = new Dictionary<int, Player>();

        private Sprite mRoleSprite;

        public PlayerMgr()
        {
            mRoleSprite = Resources.Load<Sprite>("Block");
        }
        public void OnReceiveInstruction(DanmuInstruction.Info info)
        {
            string[] text = info.text.TrimStart().Split(' ');

            switch (text[0])
            {
                case "加入":
                    if (text.Length == 1)
                    {
                        Join(info.uid, info.nickname, Vector2Kit.GetRomdomPos());
                        return;
                    }
                    CheckPosText(text[1], (x, y) =>
                    Join(info.uid, info.nickname, new Vector2(x, y)));
                    break;
                case "移动":
                    if (text.Length == 1)
                    {
                        Move(info.uid, Vector2Kit.GetRomdomPos());
                        return;
                    }
                    CheckPosText(text[1], (x, y) =>
                     Move(info.uid, new Vector2(x, y)));
                    break;
                case "攻击":

                    break;
                case "更换":

                    break;
                case "复活":

                    break;
                default:
                    Debug.Log(info.text);
                    break;
            }
        }
        private void CheckPosText(string posText, Action<float, float> callback)
        {
            string[] pos = posText.Split('[', '【', '】', ']')[1].Split(',', '，');
            if (pos.Length != 2) return;
            if (!float.TryParse(pos[0], out float x) || !float.TryParse(pos[1], out float y)) return;
            callback(x, y);
        }
        private void Move(int uid, Vector2 target)
        {
            if (mPlayers.TryGetValue(uid, out var player))
            {
                player.Move(target);
            }
            else Debug.Log("角色不存在 请创建");
        }
        private void Join(int uid, string name, Vector2 target)
        {
            if (!mPlayers.ContainsKey(uid))
            {
                var obj = new GameObject(name);
                var sp = obj.AddComponent<SpriteRenderer>();
                sp.sprite = mRoleSprite;
                var player = obj.AddComponent<Player>();
                obj.transform.localPosition = target;
                player.Move(target);
                //配置角色
                mPlayers.Add(uid, player);
                Debug.Log($"角色{obj.name}在[{target}]被创建！");
            }
            else Debug.Log("角色已存在");
        }
    }
}